package com.woniuxy.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.core.service.ArticleCommentService;
import com.woniuxy.core.mapper.ArticleCommentMapper;
import com.woniuxy.entity.ArticleComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author nanqiao
* @description 针对表【article_comment(评论互动表)】的数据库操作Service实现
* @createDate 2025-07-12 16:35:45
*/
@Service
public class ArticleCommentServiceImpl extends ServiceImpl<ArticleCommentMapper, ArticleComment> implements ArticleCommentService {

    @Autowired
    private ArticleCommentMapper articleCommentMapper;

    @Override
    public List<ArticleComment> getCommentTreeByArticleId(Long articleId) {
        List<ArticleComment> comments = baseMapper.selectCommentsByArticleId(articleId);

        Map<Long, ArticleComment> commentMap = new HashMap<>();
        for (ArticleComment comment : comments) {
            commentMap.put(comment.getId(), comment);
        }

        List<ArticleComment> rootComments = new ArrayList<>();
        for (ArticleComment comment : comments) {
            if (comment.getParentCommentId() == null || comment.getParentCommentId() == 0) {
                rootComments.add(comment);
            } else {
                ArticleComment parent = commentMap.get(comment.getParentCommentId());
                if (parent != null) {
                    if (parent.getReplies() == null) {
                        parent.setReplies(new ArrayList<>());
                    }
                    // 如果子评论没有用户信息，则继承父评论的 nickname 和 avatar
                    if (comment.getUserId() == null || comment.getNickname() == null || comment.getAvatar() == null) {
                        comment.setNickname(parent.getNickname());
                        comment.setAvatar(parent.getAvatar());
                    }
                    parent.getReplies().add(comment);
                }
            }
        }

        return rootComments;
    }

    @Override
    public boolean deleteCommentById(Long commentId) {
        return this.baseMapper.update(null, new UpdateWrapper<ArticleComment>()
                .eq("id", commentId)
                .set("is_deleted", 1)) > 0;
    }
    @Override
    public ArticleComment getCommentByIdWithUserInfo(Long commentId) {
        return baseMapper.selectCommentWithUserInfoById(commentId);
    }

}





